//
//  CityViewController.m
//  TableViewGrouped
//
//  Created by laijiawei on 14-10-10.
//
//

#import "CityViewController.h"
#import "ChineseToPinyin.h"
@interface CityViewController ()

@end

@implementation CityViewController
@synthesize tableViewDic;
@synthesize sortArray;
@synthesize searchBar;
@synthesize cityDic;
@synthesize cityarray;
@synthesize cityTableView;
@synthesize hotcityarray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
       self.navigationItem.title = @"选择城市";
    
        
    }
    
    return self;
}
- (void)viewDidLoad
{
    
    [super viewDidLoad];
    [self CustomBackButton];
    searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, 44)];
    [searchBar setBackgroundColor:[UIColor clearColor]];
    searchBar.autocorrectionType=UITextAutocorrectionTypeNo;
    searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone;
    searchBar.keyboardType=UIKeyboardTypeDefault;
    searchBar.placeholder=[NSString stringWithCString:"输入城市名字"  encoding: NSUTF8StringEncoding];
    searchBar.delegate=self;
  
    
    UIView *tableHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, 44)];
    
   // [tableHeaderView addSubview:searchBar];
    
    [self.view addSubview:searchBar];
    
   // self.cityTableView.tableHeaderView=tableHeaderView;
    
   // [[searchBar.subviews objectAtIndex:0]removeFromSuperview];
    
     _btnAccessoryView=[[UIButton alloc] initWithFrame:CGRectMake(0, 44, APP_SCREEN_WIDTH, self.view.bounds.size.height)];
    [_btnAccessoryView setBackgroundColor:[UIColor blackColor]];
    [_btnAccessoryView setAlpha:0.0f];
    
    [_btnAccessoryView addTarget:self action:@selector(ClickControlAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:_btnAccessoryView];
    

    hotcityarray=[[NSMutableArray  alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"hotCity" ofType:@"plist"]];
    
    cityarray=[[NSMutableArray  alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"city" ofType:@"plist"]];
    
    cityDic=[[NSMutableDictionary alloc]init];
    
    NSString * pinyin=nil;
    
    NSMutableArray *arr=nil;
    
    for (NSString * city in cityarray) {
        
        pinyin=[[ChineseToPinyin pinyinFromChineseString:city] substringToIndex:1];
        
        //如果包含key
        if([[cityDic allKeys]containsObject:pinyin]){
        
            arr=[cityDic objectForKey:pinyin];
            [arr addObject:city];
            [cityDic setObject:arr forKey:pinyin];
            
        }else{
        
            arr= [[NSMutableArray alloc]initWithObjects:city, nil];
            [cityDic setObject:arr forKey:pinyin];
        
        }
       
    }
    
    sortArray=[[NSMutableArray alloc]initWithObjects:@"热门", nil];
    
    sortArray= [sortArray arrayByAddingObjectsFromArray:[[cityDic allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    
    [cityDic setObject:hotcityarray forKey:@"热门"];
    
    tableViewDic=cityDic;
    
}

#pragma mark UISearchBarDelegate


- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{

    if (searchBar.text.length==0) {
        
        [_btnAccessoryView setAlpha:0.7f];
        
        searchBar.showsCancelButton=YES;//是否显示取消按钮
        
        for(id cc in [searchBar subviews])
        {
            if([cc isKindOfClass:[UIButton class]])
            {
                UIButton *btn = (UIButton *)cc;
                [btn setTitle:@"取消"  forState:UIControlStateNormal];
            }
        }
        
        
    }
    
    return YES;
    
}

#pragma mark - UISearchBarDelegate

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{

    [self controlAccessoryView:0];


}

// 当搜索内容变化时，执行该方法。很有用，可以实现时实搜索
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;{
    
    if (searchBar.text.length==0) {
        
        [_btnAccessoryView setAlpha:0.7f];
        
        searchBar.showsCancelButton=YES;//是否显示取消按钮
        

        sortArray=[[NSMutableArray alloc]initWithObjects:@"热门", nil];
        
        [cityDic removeObjectForKey:@"热门"];
        
        sortArray= [sortArray arrayByAddingObjectsFromArray:[[cityDic allKeys] sortedArrayUsingSelector:@selector(compare:)]];
        
        [cityDic setObject:hotcityarray forKey:@"热门"];
        
        tableViewDic=cityDic;
        
        [cityTableView reloadData];


    }else{
        
        NSMutableArray *arr=[[NSMutableArray alloc]init];
        

        for (NSString * city in cityarray) {
            
            if([city hasPrefix:searchText]){
            
                [arr addObject:city];
            }
        }
        tableViewDic=[NSMutableDictionary dictionaryWithObjectsAndKeys:arr,@"结果",nil];
    
        
        sortArray=[[NSMutableArray alloc]initWithObjects:@"结果", nil];
        
        [cityTableView reloadData];
     
        [UIView animateWithDuration:0.2 animations:^{
            //动画代码
            [self.btnAccessoryView setAlpha:0];
        }completion:^(BOOL finished){
                [self.searchBar setShowsCancelButton:NO animated:YES];
                [self.navigationController setNavigationBarHidden:NO animated:YES];
 
        }];

    }
    
}

// 遮罩层（按钮）-点击处理事件
- (void) ClickControlAction:(id)sender{
    
    [self controlAccessoryView:0];
   
}


// 控制遮罩层的透明度
- (void)controlAccessoryView:(float)alphaValue{
    
    [UIView animateWithDuration:0.2 animations:^{
        //动画代码
        [self.btnAccessoryView setAlpha:alphaValue];
    }completion:^(BOOL finished){
        if (alphaValue<=0) {
            [self.searchBar resignFirstResponder];
            [self.searchBar setShowsCancelButton:NO animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
            
        }
        
    }];
}


#pragma mark Table View Data Source Methods
//选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];
    NSMutableArray *array=[tableViewDic objectForKey:[sortArray objectAtIndex:section]];

    NSLog(@"%@",[array objectAtIndex:row]);
    
    [[NSUserDefaults  standardUserDefaults]setObject:[array objectAtIndex:row] forKey:@"city"];
    
    [[NSUserDefaults  standardUserDefaults]synchronize];
     [[NSNotificationCenter defaultCenter] postNotificationName:kChangeCity object:@YES];
    
    [self back:nil];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //这个方法用来告诉表格有几个分组
    return [sortArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //这个方法告诉表格第section个分组有多少行
    
       return [[tableViewDic objectForKey:[sortArray objectAtIndex:section]]count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //这个方法用来告诉某个分组的某一行是什么数据，返回一个UITableViewCell
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];

    
    static NSString *GroupedTableIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             GroupedTableIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:GroupedTableIdentifier];
    }
    
   NSMutableArray *array=[tableViewDic objectForKey:[sortArray objectAtIndex:section]];
    
    //给Label附上城市名称  key 为：C_Name
    cell.textLabel.text = [array objectAtIndex:row];
    cell.textLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:15];
    
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    //这个方法用来告诉表格第section分组的名称
    return [sortArray objectAtIndex:section];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40.0f;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    //返回省份的数组
  
    return sortArray;
}

//点击返回按钮
-(void)back:(UIButton *) button
{
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
